"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Play, Pause, Expand, Edit } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";

export default function ReadPage() {
  const router = useRouter();
  const [text, setText] = useState("视频拍摄管理系统创想家...");
  const [isScrolling, setIsScrolling] = useState(false);
  const [transformEnabled, setTransformEnabled] = useState(false);
  const [fontSize, setFontSize] = useState("48px");
  const [speed, setSpeed] = useState(200);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const scrollAreaRef = useRef<HTMLDivElement>(null);
  const intervalRef = useRef<NodeJS.Timeout>();

  const fontSizeOptions = [
    { label: "小", value: "48px" },
    { label: "中", value: "60px" },
    { label: "大", value: "90px" },
  ];

  const speedOptions = [
    { label: "慢速", value: 200 },
    { label: "正常", value: 240 },
    { label: "快速", value: 280 },
  ];

  const duration = () => {
    const chineseLength = text.split("").filter(c => c.charCodeAt(0) > 255).length;
    const englishLength = text.length - chineseLength;
    const totalLength = chineseLength + englishLength;
    return ((totalLength / speed) * 60).toFixed(2);
  };

  const startScroll = (direction: "up" | "down") => {
    setIsScrolling(true);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    
    intervalRef.current = setInterval(() => {
      if (scrollAreaRef.current) {
        const { scrollTop, scrollHeight, clientHeight } = scrollAreaRef.current;
        const maxScroll = scrollHeight - clientHeight;
        
        if (direction === "down") {
          if (scrollTop >= maxScroll) {
            scrollAreaRef.current.scrollTop = 0;
          } else {
            scrollAreaRef.current.scrollTop += 1;
          }
        } else {
          if (scrollTop <= 0) {
            scrollAreaRef.current.scrollTop = maxScroll;
          } else {
            scrollAreaRef.current.scrollTop -= 1;
          }
        }
      }
    }, 1000 / speed);
  };

  const stopScroll = () => {
    setIsScrolling(false);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
  };

  const toggleFullscreen = async () => {
    try {
      if (!isFullscreen) {
        await document.documentElement.requestFullscreen();
      } else {
        await document.exitFullscreen();
      }
      setIsFullscreen(!isFullscreen);
    } catch (err) {
      console.error('Fullscreen error:', err);
    }
  };

  useEffect(() => {
    if (scrollAreaRef.current) {
      const { scrollHeight, clientHeight } = scrollAreaRef.current;
      if (transformEnabled) {
        // 镜像模式时滚动到底部
        scrollAreaRef.current.scrollTop = scrollHeight - clientHeight;
      } else {
        // 无镜像模式时滚动到顶部
        scrollAreaRef.current.scrollTop = 0;
      }
    }
  }, [transformEnabled]);

  useEffect(() => {
    const timer = setInterval(() => {
      if (isScrolling) {
        setElapsedTime(prev => prev + 1);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [isScrolling]);

  useEffect(() => {
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  return (
    <div className="w-full h-screen bg-black overflow-hidden relative">
      {/* Controls */}
      <div className="absolute bg-gray-500 top-0 left-0 right-0 z-50 p-4 flex items-center gap-4">
        <Button onClick={() => isScrolling ? stopScroll() : startScroll(transformEnabled ? "up" : "down")}>
          {isScrolling ? <Pause className="mr-2" /> : <Play className="mr-2" />}
          {isScrolling ? "暂停" : "开始"}
        </Button>

        <div className="flex items-center gap-2">
          <Label htmlFor="mirror-mode">镜像</Label>
          <Switch
            id="mirror-mode"
            checked={transformEnabled}
            onCheckedChange={setTransformEnabled}
          />
        </div>

        <div className="flex items-center gap-2">
          <Label>字体</Label>
          <Select
            value={fontSize}
            onValueChange={setFontSize}
          >
            <SelectTrigger className="w-[100px]">
              <SelectValue placeholder="字体大小" />
            </SelectTrigger>
            <SelectContent>
              {fontSizeOptions.map(option => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex items-center gap-2">
          <Label>速度</Label>
          <Select
            value={speed.toString()}
            onValueChange={value => setSpeed(Number(value))}
          >
            <SelectTrigger className="w-[100px]">
              <SelectValue placeholder="速度" />
            </SelectTrigger>
            <SelectContent>
              {speedOptions.map(option => (
                <SelectItem key={option.value} value={option.value.toString()}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogTrigger asChild>
            <Button variant="outline">
              <Edit className="mr-2" />
              编辑文本
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>编辑提词器文本</DialogTitle>
            </DialogHeader>
            <Textarea
              className="min-h-[400px]"
              value={text}
              onChange={(e) => setText(e.target.value)}
            />
            <div className="flex justify-end">
              <Button onClick={() => setIsDialogOpen(false)}>保存</Button>
            </div>
          </DialogContent>
        </Dialog>

        <Button onClick={toggleFullscreen}>
          <Expand className="mr-2" />
          {isFullscreen ? "退出" : "全屏"}
        </Button>

        <div className="text-white ml-auto">
          {elapsedTime}s / {duration()}s
        </div>
      </div>

       {/* Highlight line */}
       <div 
          className="fixed top-1/2 left-0 right-0 h-[8rem] bg-white/10 pointer-events-none"
          style={{
            transform: 'translateY(-50%)',
          }}
        />

      {/* Text Area */}
      <div
        ref={scrollAreaRef}
        className="w-full h-screen bg-black text-white px-20 text-6xl overflow-y-scroll scroll-smooth"
      >
        <div className={transformEnabled ? "h-1/2" : "h-1/3 mt-24"} />
        <div
          className="bg-black text-left p-8 h-max"
          style={{
            fontSize,
            transform: transformEnabled ? "rotateX(180deg)" : "none",
          }}
        >
          <div className="h-max py-20 bg-blask leading-tight whitespace-pre-line">
            {text}
          </div>
        </div>
        <div className={transformEnabled ? "h-3/5" : "h-2/3"} />
      </div>
    </div>
  );
}